<div id="formDiv"></div>
<script type="text/html" id="formContent">
  <form
    lay-filter="purchaseRequisitionsFormContent"
    id="purchaseRequisitionsFormContent"
    class="layui-form open-form"
  >
    <div class="open-model">
      <div class="open-auto">
        {{# if(d.eventName!='add'){ }}
        <div class="layui-form-item layui-row">
          <input name="id" type="hidden" />
          <div class="layui-col-xs3">
            <div class="layui-form-item">
              <label class="layui-form-label">单据号</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  name="receiptsNo"
                  class="layui-input"
                  disabled
                />
              </div>
            </div>
          </div>
          <div class="layui-col-xs2">
            <div class="layui-form-item">
              <label class="layui-form-label">制单人</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  name="creatorName"
                  class="layui-input"
                  disabled
                />
              </div>
            </div>
          </div>
          <div class="layui-col-xs2">
            <div class="layui-form-item">
              <label class="layui-form-label">确认人</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  name="affirmantNickname"
                  class="layui-input"
                  disabled
                />
              </div>
            </div>
          </div>
          <div class="layui-col-xs2">
            <div class="layui-form-item">
              <label class="layui-form-label">审核人</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  name="auditorNickname"
                  class="layui-input"
                  disabled
                />
              </div>
            </div>
          </div>
          <div class="layui-col-xs2">
            <div class="layui-form-item">
              <label class="layui-form-label">状态</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  name="statusDesc"
                  class="layui-input"
                  disabled
                />
              </div>
            </div>
          </div>
        </div>
        {{# } }} {{# if(d.eventName==='audit'){ }}
        <div class="layui-form-item" id="auditBox">
          <label class="layui-form-label">审核</label>
          <div class="layui-input-block">
            <input
              name="status"
              type="radio"
              title="通过"
              value="success"
              lay-filter="getStatus"
              class="layui-input"
            />
            <input
              name="status"
              type="radio"
              title="驳回"
              value="fail"
              lay-filter="getStatus"
              class="layui-input"
            />
          </div>
        </div>
        {{# } }} {{# if(['detail','audit'].includes(d.eventName)){ }}
        <div class="layui-form-item layui-row" id="reasonInput">
          <div class="layui-inline layui-col-md4">
            <label class="layui-form-label">审核结果</label>
            <div class="layui-input-block">
              <input
                type="text"
                class="layui-input"
                id="reason"
                name="reason"
              />
            </div>
          </div>
        </div>
        {{# } }}
        <div class="layui-form-item tableContent">
          <button class="layui-btn" type="button" id="Configure">
            配置请购物资
          </button>
          <table
            class="layui-table"
            id="purchaseRequisitionsFormTable"
            lay-filter="purchaseRequisitionsFormTable"
          ></table>
        </div>
      </div>
      <div class="layui-form-item text-right">
        <button
          class="layui-btn layui-btn-primary"
          type="button"
          ew-event="closeDialog"
        >
          关闭
        </button>
        <button
          class="layui-btn"
          lay-filter="inquiryOrderInformationSubmit"
          type="button"
          lay-submit
        >
          提交
        </button>
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="purchaseRequisitionsFormTableBar">
  <button
    class="layui-btn layui-btn-danger layui-btn-xs"
    lay-event="del"
    type="button"
  >
    删除
  </button>
</script>
<script>
  layui.use(
    ["layer", "form", "table", "admin", "laydate", "upload", "laytpl"],
    async function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var config = layui.config;
      var admin = layui.admin;
      var upload = layui.upload;
      let laydate = layui.laydate;
      let laytpl = layui.laytpl;
      const nowData = { ...parentData };

      let data = nowData?.data;
      laytpl(formContent.innerHTML).render({ ...nowData }, function (html) {
        $("#formDiv").after(html);
      });
      if (nowData.eventName === "detail") {
        admin.setFormDisable("#purchaseRequisitionsFormContent", true);
      }
      if (["detail", "audit"].includes(nowData.eventName)) {
        $("#Configure").hide();
      }

      // $('#reasonInput').hide()

      const tableVal = table.render({
        elem: "#purchaseRequisitionsFormTable",
        page: false,
        limit: 999999,
        // height: 400,
        data: [],
        cols: [
          [
            { type: "numbers", title: "序号" },
            { field: "productName", align: "center", title: "物料名称" },
            { field: "skuCode", align: "center", title: "物料编号" },
            { field: "specifications", align: "center", title: "物料规格" },
            { field: "productCategory", align: "center", title: "物料分类" },
            { field: "haveQuantity", align: "center", title: "库存数量" },
            { field: "unitName", align: "center", title: "采购单位" },

            {
              field: "quantity",
              align: "center",
              title: "需求数量",
              templet: admin.setTableInput(
                "quantity",
                ["detail", "audit"].includes(nowData.eventName)
              ),
            },
            {
              field: "surplusQuantity",
              align: "center",
              title: "待采购",
              hide: ["add", "edit", "audit"].includes(nowData.eventName),
            },
            {
              field: "productCategory",
              align: "center",
              title: "已采购",
              hide: ["add", "edit", , "audit"].includes(nowData.eventName),
              templet: (d) => {
                return Number(d.quantity) - Number(d.surplusQuantity);
              },
            },
            {
              field: "productCategory",
              align: "center",
              title: "采购订单数",
              hide: ["add", "edit", , "audit"].includes(nowData.eventName),
            },
            {
              field: "productCategory",
              align: "center",
              title: "已签收",
              hide: ["add", "edit", , "audit"].includes(nowData.eventName),
            },
            {
              field: "productCategory",
              align: "center",
              title: "签收记录数",
              hide: ["add", "edit", , "audit"].includes(nowData.eventName),
            },

            // {
            //     field: 'rate',
            //     align: 'center',
            //     title: '税率(%)',
            //     templet: admin.setTableInput('rate', ['detail', 'audit'].includes(nowData.eventName))
            // },

            {
              align: "center",
              toolbar: "#purchaseRequisitionsFormTableBar",
              title: "操作",
              width: 100,
              hide: ["detail", "audit"].includes(nowData.eventName),
            },
          ],
        ],
        done: function () {
          admin.tableInputChange("purchaseRequisitionsFormTable");
        },
      });
      if (data && data.id) {
        form.val("purchaseRequisitionsFormContent", data);
        table.reload("purchaseRequisitionsFormTable", { data: data.list });
      } else {
      }

      form.on("submit(inquiryOrderInformationSubmit)", function (d) {
        let formData = { ...d.field };
        formData.purchaseRequisitionsDetails =
          table.cache["purchaseRequisitionsFormTable"];
        console.log("formData", formData);
        if (!formData.purchaseRequisitionsDetails.every((v) => v.quantity)) {
          layer.msg("请输入物料需求数量", { icon: 2, time: 1000 });
          return;
        }
        layer.load(2);
        if (formData.purchaseRequisitionsDetails.length == 0) {
          layer.closeAll("loading");
          layer.msg("请配置物料", { icon: 2, time: 1000 });
          return;
        }
        if (nowData.eventName === "add") {
          admin.req(
            "enterprise/purchase/admin/purchaseRequisitions/add",
            JSON.stringify(formData),
            function (res) {
              layer.closeAll("loading");
              if (res.code === 200) {
                layer.msg(res.msg, { icon: 1, time: 500 });
                table.reload("erpPurchaseRequisitions-table");
                layer.closeAll("page");
              } else {
                layer.msg(res.msg, { icon: 2, time: 1000 });
              }
            },
            "POST",
            false,
            "application/json"
          );
        } else if (nowData.eventName === "edit") {
          admin.req(
            "enterprise/purchase/admin/purchaseRequisitions/update",
            JSON.stringify(formData),
            function (res) {
              layer.closeAll("loading");
              if (res.code === 200) {
                layer.msg(res.msg, { icon: 1, time: 500 });
                table.reload("erpPurchaseRequisitions-table");
                layer.closeAll("page");
              } else {
                layer.msg(res.msg);
              }
            },
            "PUT",
            false,
            "application/json"
          );
        } else if (nowData.eventName === "audit") {
          if (formData.status) {
            admin.req(
              "enterprise/purchase/admin/purchaseRequisitions/audit",
              JSON.stringify(formData),
              function (res) {
                layer.closeAll("loading");
                if (res.code === 200) {
                  layer.msg(res.msg, { icon: 1, time: 500 });
                  table.reload("erpPurchaseRequisitions-table");
                  layer.closeAll("page");
                } else {
                  layer.msg(res.msg);
                }
              },
              "POST",
              false,
              "application/json"
            );
          } else {
            layer.closeAll("loading");
            layer.msg("请选择审核通过还是驳回");
          }
        }
        return false;
      });

      table.on("tool(purchaseRequisitionsFormTable)", function (obj) {
        var d = obj.data; // 获取当前行的数据
        var layEvent = obj.event; // 获取事件名（edit 或 del）
        if (obj.tr) {
          obj.tr.on("click", function (e) {
            e.preventDefault(); // 防止默认行为
          });
        }
        if (layEvent == "del") {
          const index = $(obj.tr[0]).data("index");
          let list = table.cache["purchaseRequisitionsFormTable"].filter(
            (v) => {
              return v["LAY_TABLE_INDEX"] != index;
            }
          );
          table.reload("purchaseRequisitionsFormTable", {
            data: list,
          });
        }
      });
      $("#Configure").click(function () {
        admin.formOpen({
          area: "90%",
          offset: "50px",
          title: "配置物料信息",
          path: "components/purchase/skuTableForm.html",
          success: function () {
            parentData.cacheList = [
              ...table.cache["purchaseRequisitionsFormTable"],
            ];
            parentData.materialNatureList = ["1"];

            console.log(parentData.cacheList);
            if (parentData.cacheList.length > 0) {
              parentData.notInListIds = table.cache[
                "purchaseRequisitionsFormTable"
              ]
                .map((v) => {
                  // if (v.id) return v.id
                  if (v.productDetailId) return v.productDetailId;
                })
                .join(",");
            } else {
              parentData.notInListIds = "";
            }
          },
          end: function () {
            if (childData.list) {
              const newData = childData.list || [];
              newData.forEach((v) => {
                v.specifications = v.skuSpec;
                v.productName = v.skuName;
                v.productCategory = v.productTypeId;
                v.productCategoryName = v.productTypeName;
                v.unitName = v.mainUnitName;
              });
              const oldData = table.cache["purchaseRequisitionsFormTable"];
              const list = [...oldData, ...newData];
              table.reload("purchaseRequisitionsFormTable", {
                data: list, // 设置新的数据
              });
            }
          },
        });
      });
    }
  );
</script>

<style>
  /*#purchaseRequisitionsFormContent .layui-form-label {*/
  /*    width: 110px;*/
  /*}*/

  /*#purchaseRequisitionsFormContent .layui-input-block {*/
  /*    margin-left: 140px;*/
  /*}*/

  #purchaseRequisitionsFormContent .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }
</style>
